<?php
class DBManager {

	private $host;
	private $user;
	private $pass;
	private $database;
	private $conn;

	private static $instance = null;

	final static function getInstance() {
		if (self::$instance == null) {
			self::$instance = new DBManager();
		}
		return self::$instance;
	}

	private function __construct() {
		try {
			$properties = IniParser::parseIniFile();
			$this->host = $properties[IniParser::INI_FILE_ASSETS_HOST];
			$this->user = $properties[IniParser::INI_FILE_ASSETS_USER];
			$this->pass = $properties[IniParser::INI_FILE_ASSETS_PASSWORD];
			$this->database = $properties[IniParser::INI_FILE_ASSETS_DATABASE];
		} catch (Exception $e) {
			Log::logError($e);
		}
	}

	private function __clone() {
	}

	public function callProcedure($procedure, $params) {
		if ($this->conn == null) {
			$this->connect();
		}
		try {
			$query = "call " . $procedure . "(";
			if (!empty($params)) {
				for ($i = 0; $i < sizeof($params); $i++) {
					$query = $query . "?";
					if ($i != sizeof($params) - 1) {
						$query = $query . ",";
					}
				}
			}
			$query .= ");";
			$this->connect();
			if ($this->conn instanceof PDO) {
				$stmt = $this->conn->prepare($query);
				foreach ($params as $key => $param) {
					if (empty($param) && $param != 0 && $param != "0") {
						$stmt->bindValue($key + 1, null, PDO::PARAM_NULL);
					} else {
						$stmt->bindValue($key + 1, $param);
					}
				}
				$stmt->execute();
				return $stmt->fetchAll(PDO::FETCH_ASSOC);
			} else {
				Log::logInfo("Cannot connect to DB");
			}
		} catch (Exception $e) {
			Log::logError($e);
		}
		return array();
	}

	private function connect() {
		$driver = "mysql:host=" . $this->host . ";dbname=" . $this->database;
		$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
		try {
			$this->conn = new PDO ($driver, $this->user, $this->pass, $options);
			$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		} catch (Exception $e) {
			Log::logError($e);
		}
	}
}

?>